<?php

namespace Frieza\Modules\Complain\Controllers;


use Doraemon\model\Complain\FeedBack;
use Doraemon\model\Es\UserPortrait;
use Doraemon\model\Member;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\tools\Log;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;

use Doraemon\model\Complain\FeedBack as mFeedBack;
use Doraemon\service\Complain\FeedBack as sFeedBack;

class FeedBackController extends Controller
{
    const PAGE_SIZE = 50;

    /**
     *  反馈列表
     */
    public function list(Content $content, Request $request)
    {
        $params = [
            'page' => $request->input('page', 1),
            'per_page' => $request->input('per_page', 20),
            'content' => $request->input('content', ''),
            'uid' => $request->input('uid', ''),
            'uname' => $request->input('uname', ''),
            'status' => $request->input('status', ''),
            'client_type' => $request->input('client_type', ''),
            'app_ver' => $request->input('app_ver', ''),
            'addtime' => $request->input('addtime', ''),
            'vip_level' => $request->input('vip_level', '2')
        ];

        return $content
            ->header('反馈管理')
            ->breadcrumb(
                ['text' => '反馈管理列表', 'url' => '/admin/complain/feedback/list']
            )
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>")
            ->body($this->listAction($params));
    }

    /**
     * 反馈列表展示
     */
    private function listAction($params = [])
    {
        $level = $params['vip_level'];
        $infos = sFeedBack::getList($params);
        $data = [];
        foreach ($infos['data'] as $key => $info) {
            if ($info['vip_level'] == $level || $level == FeedBack::LEVEL_ALL) {
                $data[$key] = $info;
            }
        }
        $gridModel = new pGridDataModel($data, $infos['total'], [
            'perPage' => $params['per_page'],
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($params) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->tools(function ($tools) use ($params) {
                $export_url = http_build_query($params);
                $url = url('/admin/complain/feedback/export?'.$export_url);
                $tools->append('<div class="btn-group download" style="margin-right: 10px"><a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="'.$url.'"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a></div>');
                $tools->append("<p class='btn btn-sm btn-success' style='float: right;color:#FFFFFF'><a href='/admin/complain/feedback/normalword/list/' style='float: right;color:#FFFFFF'><i class='fa fa-flag'>&nbsp;&nbsp;编辑常用语</a></i></p>");
            });

            // 筛选项
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->dropDown('id', [
                    'content' => '关键词',
                    'uid' => '用户uid',
                    'uname' => '用户昵称'
                ]);
                $filter->in('vip_level', '反馈类型')->radio(mFeedBack::LEVEL);
                $filter->in('status', '类型')->radio(mFeedBack::STATUS);
                $filter->in('client_type', '系统类型')->radio(mFeedBack::CLIENT_TYPE);
                $filter->equal('app_ver', '系统版本')->select(sFeedBack::listVersionByPhoneType());
                $filter->between('addtime', '时间')->datetime();
            });
            $grid->column('id');
            $grid->column('反馈类型')->display(function () {
                if ($this->vip_level == mFeedBack::LEVEL_5) {
                    $str = '<p style="color: #ce192f">超级住友反馈：</p>';
                } else {
                    $str = '<p>普通住友反馈：</p>';
                }
                return $str;
            });
            $grid->column('用户')->display(function () {
                $userArr = $this->user;
                if ($this->vip_level == FeedBack::LEVEL_5) {
                    $userStr = '<a href="/admin/user/Detail/' . $userArr[0]['uid'] . '" style="color: #ce192f"><i class="fa fa-dollar fa-fw" style="color: #ce192f "></i><i class="fa fa-user fa-fw" style="color:#ce192f;"></i>' . $userArr[0]['nick'] . '(' . $userArr[0]['uid'] . ')</a>';
                } else {
                    $userStr = '<a href="/admin/user/Detail/' . $userArr[0]['uid'] . '"><i class="fa fa-user fa-fw"></i>' . $userArr[0]['nick'] . '(' . $userArr[0]['uid'] . ')</a>';
                }
                $str = '';
                if (isset($this->android_phone)) {
                    $str = "<br />手机类型：" . $this->android_phone;
                }
                return $userStr . "<br \>" . '手机型号: ' . mFeedBack::CLIENT_TYPE[$this->client_type] . ' ' . $this->client_os_ver . "<br />" .
                    '应用版本：' . $this->app_ver . $str;
            });
            $grid->cloumn('内容')->display(function () {
                $content = $this->message;
                $str = '';
                if ($content['pic_id']) {
                    $str = '<img src="' . $this->img_url . '" class="img" style="height:150px;" />';
                } else {
                    $str = $content['message'];
                }
                return $this->addtime . " :<br />" . $str;
            })->width(500);
            $grid->column('status', '状态')->label([
                '未处理' => 'danger',
                '处理中' => 'warning',
                '已回复' => 'success',
            ]);
            $grid->column('', '状态')->display(function () {
                $userArr = $this->user;
                return '<a href="/admin/complain/feedback/list/' . $userArr[0]['uid'] . '" target="_blank"><i class="fa fa-cog fa-spin"></i>处理</a>';
            });
        });

        Admin::script($this->imgScript());

        return $listGrid->render();
    }

    /**
     * 反馈处理
     */
    public function handleFeedback($uid = 0, Request $request, Content $content)
    {
        return $content
            ->header('反馈处理')
            ->breadcrumb(
                [
                    'text' => '反馈管理列表',
                    'url' => '/complain/feedback/list'
                ],
                ['text' => "反馈处理"]
            )
            ->row(function (Row $row) use ($uid) {
                $row->column(6, $this->editActionList($uid));
                $row->column(6, $this->editActionForm($uid));
            });
    }

    /**
     * 反馈处理--内容展示
     */
    private function editActionList($uid = 0)
    {
        $info = sFeedBack::handleFeedback($uid);
        $gridModel = new pGridDataModel($info['data']);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->disableActions();
            $grid->disableFilter();
            $grid->tools(function ($tools) use ($id) {

                // $tools->append("<p class='btn btn-sm btn-success' style='float: right;color:#FFFFFF'><a href='/admin/complain/feedback/normalword/list/' style='float: right;color:#FFFFFF'><i class='fa fa-flag'>&nbsp;&nbsp;编辑常用语</a></i></p>");

            });
            $grid->disablePagination();
            $grid->column('message', '聊天内容')->display(function () {
                return $this->message;
            });
        });

        return $listGrid;
    }

    /**
     * 反馈处理--信息编辑
     */
    private function editActionForm($uid = 0)
    {
        $this->wordChoose();
        $info = sFeedBack::handleFeedback($uid);
        $word = sFeedBack::getNormalWord();
        $form = new  Form($info);
        $form->display('usermessage', '用户');
        $form->textarea('message', '消息：');
        $form->select('normalword', '常用语：')->options($word)
            ->default('-1');
        $form->checkbox('status', '是否处理')->options([mFeedBack::STATUS_HANDLE => '处理中']);
        $form->action("/admin/complain/feedback/list/$uid");
        return $form;
    }

    public function saveFeedback($uid, Request $request)
    {
        $params = [
            'message' => $request->input('message', ''),
            'normalword' => $request->input('normalword', ''),
            'status' => $request->input('status', ''),
        ];

        $result = sFeedBack::saveFeedback($uid, $params);

        if ($result['code']) {
            $success = new MessageBag([
                'title' => $result['message'],
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => $result['message'],
            ]);

            return back()->with(compact('error'));
        }

    }

    /**
     * 常用语编辑
     */
    public function editNormalWord(Content $content)
    {
        $tab = new Tab();
        $tab->add("常用语编辑", $this->editNormalWordAction());
        return $content
            ->header('反馈管理')
            ->breadcrumb(
                [
                    'text' => '反馈管理列表',
                    'url' => '/complain/feedback/list'
                ],
                ['text' => "常用语编辑"]
            )
            ->body($tab);
    }

    /**
     * 常用语编辑--信息展示
     */
    private function editNormalWordAction()
    {
        $info = sFeedBack::editNormalWord();
        $form = new Form($info);
        $form->textarea('text', '常用语')->help('请用换行隔开每条常用语');
        $form->action('/admin/complain/feedback/normalword/list/save');
        return $form->render();
    }

    /**
     * 常用语编辑--信息保存
     */
    public function saveNormalWord(Request $request)
    {
        $text = $request->input('text', '');
        $result = sFeedBack::editNormalWord($text);

        if ($result) {
            return back()->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } else {
            return back()->with('error', new MessageBag([
                'title' => '操作失败'
            ]));
        }

    }

    public function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });

SCRIPT;
    }

    private function wordChoose()
    {
        Admin::script(
            <<<SCRIPT
            $('.normalword').on('change',function(){
            var option =$(this).find("option:selected").text();
            var message=  $(".message").val();
            $(".message").val(message+option);       
         });
SCRIPT
        );
    }

    public function export(Request $request)
    {
        $params = [
            'content' => $request->input('content', ''),
            'uid' => $request->input('uid', ''),
            'uname' => $request->input('uname', ''),
            'status' => $request->input('status', ''),
            'client_type' => $request->input('client_type', ''),
            'app_ver' => $request->input('app_ver', ''),
            'addtime' => $request->input('addtime', ''),
            'vip_level' => $request->input('vip_level', '2')
        ];

        //导出符合筛选的所有数据
        $params['page'] = 1;
        $params['per_page'] = PHP_INT_MAX;

        $info = sFeedBack::getExportList($params);
        $res = [];
        if (!empty($info['data'])) {
            foreach ($info['data'] as $k => $v) {
                //反馈类型
                if ($v['vip_level'] == mFeedBack::LEVEL_5) {
                    $res[$k]['feedback_type'] = '超级住友反馈';
                } else {
                    $res[$k]['feedback_type'] = '普通住友反馈';
                }
                //用户uid
                $res[$k]['uid'] = $v['uid'];
                //用户昵称
                $res[$k]['user_name'] = $v['user']['nick'];
                //手机型号
                $res[$k]['phone_type'] = mFeedBack::CLIENT_TYPE[$v['client_type']] . ' ' . $v['client_os_ver'];
                //应用版本
                $res[$k]['app_ver'] = $v['app_ver'];
                //反馈时间
                $res[$k]['addtime'] = $v['addtime'];
                //反馈描述
                $res[$k]['content'] = self::filterEmoji($v['message']['message']);
            }
        }
        if(empty($res)){
            $error = new MessageBag([
                'title' => '没有数据',
            ]);
            return back()->with(compact('error'));
        }
        $reason = "反馈管理";
        $header = ["反馈类型","用户uid","用户昵称","手机型号", "应用版本", "反馈时间", "反馈描述"];
        $excelObj = new DownExcel();
        $excelObj->setFileName($reason);
        $excelObj->setSheetTitle($reason);
        //设置列宽
        $widths = ['A' => 15, 'B' => 10,'C' => 15,'D' => 10,'E' => 10,'F' => 15,'G' => 30];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        $excelObj->create($res, $header);
    }

    private static function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}
